package cn.com.cfae.iras.doc.analyze.components.rationality;

import cn.com.cfae.iras.doc.analyze.components.BaseComponent;
import cn.com.cfae.iras.doc.analyze.components.beans.ComponentResult;
import cn.com.cfae.iras.doc.analyze.handUtil.HandingData;
import cn.com.cfae.iras.doc.analyze.keys.UnitType;
import cn.com.cfae.iras.doc.analyze.parse.kv.KVText;
import cn.com.cfae.iras.doc.analyze.parse.kv.TextLayout;
import cn.com.cfae.iras.doc.analyze.parse.model.ChapterModel;
import cn.com.cfae.iras.doc.analyze.parse.model.DocumentModel;
import cn.com.cfae.iras.doc.analyze.parse.model.ExtractBizModel;
import cn.com.cfae.iras.doc.analyze.parse.model.ExtractItem;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 内容合理性检查 （改到R1018）
 * （M.5-2）子表
 * M-6
 * 1、从M-6章节获取对外担保金额、净资产
 * 2、如果“对外担保金额”、“净资产”不存在，提示缺失
 * 3、计算公式：对外担保金额/净资产
 *
 */
@Component("R1016")
@Scope("prototype")
public class R1016 extends BaseComponent {
    private static Logger log = LoggerFactory.getLogger(R1016.class);
    @Autowired
    private HandingData handingData;
    @Override
    public List<ComponentResult> handlerM() {
        log.info("获取R1016组件M");
        //"债务融资工具信用增进"
        List<ComponentResult> componentResults = checkRulesR1016("M-8","M-8","M-8",getRuleTitle());
        return componentResults;
    }

    @Override
    public List<ComponentResult> handlerBM() {
        log.info("获取R1016组件BM");
        List<ComponentResult> componentResults = checkRulesR1016("BM-8","BM-8","BM-8",getRuleTitle());
        return componentResults;
    }

    @Override
    public List<ComponentResult> handlerDM() {
        log.info("获取R1016组件DM");
        List<ComponentResult> componentResults = checkRulesR1016("DM-8","DM-8","DM-8",getRuleTitle());
        return componentResults;
    }

    @Override
    public List<ComponentResult> handlerBDM() {
        log.info("获取R1016组件BDM");
        List<ComponentResult> componentResults = checkRulesR1016("BDM-8","BDM-8","BDM-8",getRuleTitle());
        return componentResults;
    }

    private List<ComponentResult> checkRulesR1016(String model,String catalogId,String chapterId,String ruleName){
        DocumentModel extractData = super.getExtractData();
        List<ComponentResult> componentResults = new ArrayList<>();
        ComponentResult componentResult = null;
        ExtractItem extractItem = null;
        int dPageNum = 0;
        int jPageNum = 0;
        List<ComponentResult.TextPosition> dContentAndPositionList = null;
        List<ComponentResult.TextPosition> jContentAndPositionList = null;
        boolean dwdbjeFlag = false;
        boolean jzcFlag = false;
        Double dwdbjeDouble = 0.0;
        Double jzcDouble = 0.0;
        int startPage = 0;
        String dwdbjeText = null;
        String jzcText = null;
        String[] keywords = new String[]{"对外担保金额","净资产"};
        boolean isAllErr = false;


        String dwdbjeUnit = null;
        String jzcUnit = null;

        try {
            if (extractData!=null){
                ChapterModel chapterModel = extractData.getChapterModel(model);
                startPage = chapterModel!=null?chapterModel.getStartPage():0;
                //对外担保金额
                extractItem = getExtractItem(extractData,model,"DWDB","DWDBJE");
                if (extractItem!=null){
                    KVText value = extractItem.getValue();
                    dwdbjeText = value!=null?value.getText():null;
                    List<TextLayout> textLayouts = value != null ? value.getTextLayoutList() : null;
                    dPageNum =CollectionUtils.isNotEmpty(textLayouts) ? textLayouts.get(0).getPageNumber() : startPage;
                    dContentAndPositionList = value!=null?getContentAndPositionList(value):null;
                }
                dPageNum = dPageNum!=0?dPageNum:startPage;


                //净资产  所有者权益合计
                Map<String, Map<String, ExtractItem>> zcfz = chapterModel.getModel("ZCFZ").getTables();
                List<String> years = new ArrayList<>();
                if (zcfz!=null&&!zcfz.isEmpty()){
                    for (String fz : zcfz.keySet()){
                        years.add(fz);
                    }
                    Collections.sort(years);
                    Map<String, ExtractItem> zcfzYear = null;
                    if (CollectionUtils.isNotEmpty(years)){
                        zcfzYear  = chapterModel.getModel("ZCFZ").getTable(years.get(years.size()-1));
                    }

                    if (zcfzYear!=null){
                        extractItem = zcfzYear.get("SYZQYHJ");
                        jzcUnit = extractItem!=null?extractItem.getUnit():"万元";
                        jzcUnit = jzcUnit!=null?jzcUnit:"万元";
                        KVText value = extractItem!=null?extractItem.getValue():null;
                        jzcText = value!=null?value.getText():null;
                        List<TextLayout> textLayouts = value != null ? value.getTextLayoutList() : null;
                        jPageNum = CollectionUtils.isNotEmpty(textLayouts)?textLayouts.get(0).getPageNumber():startPage;
                        jContentAndPositionList = value!=null?getContentAndPositionList(value):null;
                    }
                }
                jPageNum = jPageNum!=0?jPageNum:startPage;
            }

            //获取对外担保金额 及 单位
            String dwdbjeMoneyText = null;
            if (StringUtils.isNotEmpty(dwdbjeText)){
                dwdbjeFlag = true;
                if (dwdbjeText.equals("——")||dwdbjeText.equals("-")){
                    dwdbjeMoneyText = null;
                }else {
                    String regexUnit = "[\\u4e00-\\u9fa5]";
                    String regex = "[\\u4e00-\\u9fa5a-zA-Z]";
                    StringBuffer unit = new StringBuffer();
                    StringBuffer money = new StringBuffer();
                    //获取单位
                    Pattern pattern = Pattern.compile(regexUnit);
                    Matcher m = pattern.matcher(dwdbjeText);
                    while (m.find()){
                        unit.append(m.group());
                    }
                    if (StringUtils.isNotEmpty(unit.toString())){
                        dwdbjeUnit = unit.toString();
                    }else {
                        dwdbjeUnit = "万元";
                    }

                    //获取金额
                    pattern = Pattern.compile(regex);
                    m = pattern.matcher(dwdbjeText);
                    while (m.find()){
                        money.append(m.replaceAll(""));
                    }
                    if (StringUtils.isNotEmpty(money.toString())){
                        String moneyText = money.toString();
                        moneyText = moneyText.replaceAll("\\s+","");
                        moneyText = moneyText.replaceAll(",","");
                        dwdbjeMoneyText = moneyText;
                    }else {
                        dwdbjeText = dwdbjeText.replaceAll("\\s+","");
                        dwdbjeMoneyText =dwdbjeText.replaceAll(",","");
                    }
                }
            }



            // 获取 所有者权益合计 金额 及  单位
            String jzcMoneyText = null;
            if (StringUtils.isNotEmpty(jzcText)){
                jzcFlag = true;
                //获取单位
                //获取金额
                if (jzcText.equals("——")||jzcText.equals("-")){
                    jzcMoneyText = null;
                }else {
                    jzcText = jzcText.replaceAll("\\s+", "");
                    jzcMoneyText = jzcText.replaceAll(",","");
                    jzcMoneyText = jzcMoneyText.trim();
                }
            }

            //计算之前 判断单位是否相同、都转换成 万元 进行计算
            if (StringUtils.isNotEmpty(dwdbjeUnit)&&StringUtils.isNotEmpty(jzcUnit)){
                if (!dwdbjeUnit.equals(jzcUnit)){
                    if (StringUtils.isNotEmpty(dwdbjeMoneyText)){
                        dwdbjeMoneyText = getMoneyToThousandYuan(dwdbjeUnit,dwdbjeMoneyText);
                    }
                    if (StringUtils.isNotEmpty(jzcMoneyText)){
                        jzcMoneyText = getMoneyToThousandYuan(jzcUnit,jzcMoneyText);
                    }
                }
            }

            if (dwdbjeFlag){
                componentResult = handingData.getComponentResult(catalogId,chapterId, ruleName, "对外担保金额为:"+dwdbjeText, "已抽取", false, getRegulationId(), dPageNum, dContentAndPositionList, "01");
                componentResults.add(componentResult);
            }else {
                isAllErr = true;
                componentResult = handingData.getComponentResult(catalogId,chapterId, ruleName, "对外担保金额", "未识别,建议人工核对", true, getRegulationId(), dPageNum, dContentAndPositionList, "03");
                componentResults.add(componentResult);
            }
            if (jzcFlag){
                componentResult = handingData.getComponentResult(catalogId,chapterId, ruleName, "净资产为:"+jzcText, "已抽取", false, getRegulationId(), jPageNum, jContentAndPositionList, "01");
                componentResults.add(componentResult);
            }else {
                isAllErr = true;
                componentResult = handingData.getComponentResult(catalogId,chapterId, ruleName, "净资产", "未识别,建议人工核对", true, getRegulationId(), jPageNum, jContentAndPositionList, "03");
                componentResults.add(componentResult);
            }

            if (StringUtils.isNotEmpty(dwdbjeMoneyText) && StringUtils.isNotEmpty(jzcMoneyText)){
                BigDecimal dwdbjeBigDecimal = new BigDecimal(dwdbjeMoneyText);
                BigDecimal jzcBigDecimal = new BigDecimal(jzcMoneyText);

                if (jzcBigDecimal.compareTo(new BigDecimal("0"))==0){
                    isAllErr = true;
                    componentResult = handingData.getComponentResult(catalogId,chapterId, ruleName, "对外担保金额与净资产比例", "净资产为0无法计算", false, getRegulationId(), dPageNum, dContentAndPositionList, "03");
                    componentResults.add(componentResult);
                }else {
                    BigDecimal jgDivide =  dwdbjeBigDecimal.divide(jzcBigDecimal,4, BigDecimal.ROUND_HALF_UP);
                    componentResult = handingData.getComponentResult(catalogId,chapterId, ruleName, "对外担保金额与净资产比例", jgDivide.toPlainString(), false, getRegulationId(), dPageNum, dContentAndPositionList, "01");
                    componentResults.add(componentResult);
                }
            }else {
                isAllErr = true;
                componentResult = handingData.getComponentResult(catalogId,chapterId, ruleName, "对外担保金额与净资产比例", "未识别,建议人工核对", true, getRegulationId(), dPageNum, dContentAndPositionList, "03");
                componentResults.add(componentResult);
            }

            if (isAllErr){
                if (CollectionUtils.isNotEmpty(componentResults)){
                    for (ComponentResult result:componentResults){
                        result.setExist("03");
                    }
                }
            }
        }catch (Exception e){
            componentResults.clear();
            for (String key :keywords){
                componentResult = handingData.getComponentResult(catalogId,chapterId, ruleName, key, "未识别,建议人工核对", true, getRegulationId(), startPage, dContentAndPositionList, "03");
                componentResults.add(componentResult);
            }
            componentResult = handingData.getComponentResult(catalogId,chapterId, ruleName, "对外担保金额与净资产比例", "未识别,建议人工核对", true, getRegulationId(), startPage, dContentAndPositionList, "03");
            componentResults.add(componentResult);
            log.error(e.getMessage(),e);
        }

        return componentResults;
    }

    private ExtractItem getExtractItem(DocumentModel extractData, String chapter, String model, String key){
        ExtractItem extractItem  = null;
        if (extractData!=null){
            ChapterModel chapterModel = extractData.getChapterModel(chapter);
            if (chapterModel != null){
                ExtractBizModel extractMode = chapterModel.getModel(model);
                if (extractMode!=null){
                    extractItem = extractMode.getExtractItem(key);
                }
            }
        }
        return extractItem;
    }
    private String getMoneyToThousandYuan(String unit,String money){
        String moneyString = null;
        BigDecimal moneyBigDecimal = new BigDecimal(money);

        switch (unit){
            case "元":
                BigDecimal yuanBigDecimal = new BigDecimal(10000);
                BigDecimal yuanDivide = moneyBigDecimal.divide(yuanBigDecimal);
                moneyString = yuanDivide.toPlainString();
                break;
            case "千元":
                BigDecimal thousandYuanBigDecimal = new BigDecimal(10);
                BigDecimal thousandYuanDivide = moneyBigDecimal.divide(thousandYuanBigDecimal);
                moneyString = thousandYuanDivide.toPlainString();
                break;
            case "万元":
                moneyString = money;
                break;
            case "亿元":
                BigDecimal hundredMillionBigDecimal = new BigDecimal(10000);
                BigDecimal hundredMillionnDivide = moneyBigDecimal.multiply(hundredMillionBigDecimal);
                moneyString = hundredMillionnDivide.toPlainString();
                break;
        }
        return moneyString;
    }
}
